package cn.rubintry.bug.hunting.activity

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import cn.rubintry.bug.common.base.BaseActivity
import cn.rubintry.bug.hunting.R
import cn.rubintry.bug.hunting.adapter.HistoryAdapter
import cn.rubintry.bug.hunting.databinding.ActivityHistoryBinding
import cn.rubintry.bug.hunting.decoration.VerticalSpaceItemDecoration
import cn.rubintry.bug.hunting.common.http.viewmodel.HistoryViewModel
import cn.rubintry.bug.hunting.pojo.HistoryModel

import com.blankj.utilcode.util.ToastUtils
import com.chad.library.adapter4.BaseQuickAdapter

class HistoryActivity : BaseActivity<ActivityHistoryBinding>(), View.OnClickListener {

    private val historyViewModel: HistoryViewModel by viewModels<HistoryViewModel>()

    private var adapter: HistoryAdapter ?= null

    override fun bindingClazz(): Class<ActivityHistoryBinding> {
        return ActivityHistoryBinding::class.java
    }

    override fun getActivityParams() {

    }

    override fun initView() {
        binding?.imgBack?.setOnClickListener(this)
        adapter = HistoryAdapter(mutableListOf())
        binding?.rvHistory?.layoutManager = LinearLayoutManager(this)
        binding?.rvHistory?.isNestedScrollingEnabled = false
        binding?.rvHistory?.adapter = adapter
        adapter?.setOnItemClickListener { adapter, view, position ->
            val intent = Intent(this@HistoryActivity , ArticleDetailActivity::class.java)
            val params = Bundle()
            params.putString("articleId" , (adapter.getItem(position) as HistoryModel).articleId)
            intent.putExtras(params)
            startActivity(intent)
        }
        historyViewModel.getHistory()
    }

    override fun onResume() {
        super.onResume()
        historyViewModel.getHistory()
    }

    override fun observeData() {
        historyViewModel.historyData.observe(this){
            if(it.code == "0"){
                if(binding?.rvHistory?.itemDecorationCount == 0){
                    binding?.rvHistory?.addItemDecoration(VerticalSpaceItemDecoration(15 , it.total.toInt()))
                }
                adapter?.submitList(it.data)

            }else{
                ToastUtils.showShort(it.message)
            }
        }
    }

    override fun onNetWorkError(msg: String?) {

    }

    override fun onClick(v: View?) {
        when(v){
            binding?.imgBack -> {
                finish()
            }
        }
    }

}